﻿using System;
using System.Collections.Generic;
using System.Text;

namespace SharpSoft.WPF.Controls
{
    /// <summary>
    /// 时间跟踪器
    /// </summary>
    public class TimeTracker
    {
        #region Constructors

        public TimeTracker()
        {
            firstTime = lastTime = DateTime.Now;
            this.Interval = TimeSpan.FromSeconds(1) / 30;
        }

        public TimeTracker(TimeSpan interval)
        {
            firstTime = lastTime = DateTime.Now;
            this.Interval = interval;

        }
        private DateTime firstTime;
        private DateTime lastTime;
        #endregion

        #region Events

        /// <summary>
        /// 在指定的时间间隔后触发
        /// </summary>
        public event EventHandler TimerFired;

        #endregion

        /// <summary>
        /// 重置时间计数器，从当前时间点开始计时。
        /// </summary>
        public void Reset()
        {
            lastTime = firstTime = DateTime.Now;
        }
        /// <summary>
        /// 更新时间计数，如果超出了指定的时长则触发<see cref="TimerFired"/>事件。
        /// </summary>
        /// <returns></returns>
        public double Update()
        {
            var currentTime = DateTime.Now;

            var diffTime = currentTime - lastTime;
            DeltaSeconds = diffTime.TotalSeconds;


            if (diffTime >= Interval)
            {
                TimerFired?.Invoke(this, null);
                lastTime = currentTime;
            }

            return DeltaSeconds;
        }

        #region Properties
        /// <summary>
        /// 获取或设置最小时间间隔
        /// </summary>
        public TimeSpan Interval { get; set; }
        /// <summary>
        /// 获取已持续的时间
        /// </summary>
        public TimeSpan ElapsedTime
        {
            get
            {
                return DateTime.Now - firstTime;
            }
        }
        /// <summary>
        /// 时间变化量，计为秒数（相对与上一帧）
        /// </summary>
        public double DeltaSeconds { get; private set; }

        #endregion
    }
}
